package com.beney.client.handler;

import com.beney.codec.MessagePacketDecoder;
import com.beney.codec.MessagePacketEncoder;
import com.beney.message.MessageDispatcher;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ClientHandlerInitializer extends ChannelInitializer<Channel> {

    /**
     * 心跳时限
     */
    @Value("${netty.client.heartbeat}")
    private Integer heartbeatSec;

    /**
     * 等待读的超时时间
     */
    @Value("${netty.client.read-timeout}")
    private Integer readTimeout;

    @Autowired
    private ClientHandler clientHandler;

    @Autowired
    private MessageDispatcher messageDispatcher;

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ch.pipeline()
                // TODO: idle 深入研究
                .addLast(new IdleStateHandler(heartbeatSec, 0, 0))
                .addLast(new ReadTimeoutHandler(readTimeout))
                // 编码器
                .addLast(new MessagePacketEncoder())
                // 解码器
                .addLast(new MessagePacketDecoder())
                // 消息分发
                .addLast(messageDispatcher)
                .addLast(clientHandler);
    }
}
